const Database = require('../mongodb/index.js');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

const { ObjectId } = require('mongodb');
const sendEmail = require('./utils/email.js');
const { getTime, getjwt, getYMDHMS } = require('./utils/index.js');
// const db = new Database();
// let users = null
// // 查询数据
// try {
//   // // 连接数据库
//   await db.connect();
//   users = await db.findOne('users', { Email: user.email });

//   await db.disconnect();

// } catch (error) {
//   res.send({ code: 500, message: "数据库异常!" })
//   return
// }
userCode = {}
userJwt = {}
module.exports = {
  async home (req, res, next) {
    const db = new Database();
    let list = []
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      list = await db.find('ArticleList');

      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.render('index', { content: JSON.stringify(list) })
  },
  async login (req, res, next) {
    const requser = req.body
    const db = new Database();
    let user = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      user = await db.findOne('users', { Username: requser.username });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
    }
    if (!user) {
      res.send({ code: 403, message: "账号未注册!" })
      return
    }
    if (user.Password === requser.password) {
      // 签名token
      const secret = crypto.randomBytes(20).toString('hex');; // 应该是一个复杂的随机字符串
      userJwt[user._id] = secret
      const expiresIn = '1h'; // token有效时长
      const token = jwt.sign(user, secret, { expiresIn });
      res.send({
        code: 200, message: "登录成功!", data: {
          username: user.Username,
          token,
          Avatar: user.Avatar,
          userId: user._id
        }
      })
      return
    } else {
      res.send({ code: 40001, message: "密码错误!" })
      return
    }
  },
  async sendEmail (req, res, next) {
    const number = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    console.log(`${number}`)
    userCode[`${req.body.email}`] = number;
    sendEmail(req.body.email, userCode[req.body.email])
    setTimeout(() => {
      userCode[req.body.email] = ''
    }, 300000)
    res.send({ code: 200, message: '发送成功!' })
  },
  async register (req, res, next) {
    const user = req.body
    if (!user) return
    if (userCode[user.email] === '') {
      res.send({ code: 403, message: `验证码已过期!` })
      return
    }
    if (userCode[user.email] !== user.code) {
      res.send({ code: 40001, message: `验证码错误!` })
      return
    }
    const db = new Database();
    let users = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      users = await db.findOne('users', { Email: user.email });
      if (users) {
        res.send({ code: 403, message: "邮箱已被注册!" })
        return
      }
      // 插入数据
      const insertResult = await db.insertOne('users', {
        "Username": user.username,
        "Password": user.password,
        "Email": user.email,
        "Avatar": "http://localhost:3000/img/1.png",
        "CreationDate": getTime()
      });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }

    res.send({ code: 200, message: "注册成功" })
  },
  async ArticleList (req, res, next) {
    const db = new Database();
    let list = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      list = await db.find('ArticleList');
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.send({ code: 200, message: "获取成功!", data: list })

  },
  async ArticleDetails (req, res, next) {
    console.log(req.query)

    const db = new Database();
    let Article = null
    let user = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      Article = await db.findOne('ArticleList', { _id: new ObjectId(req.query.ArticleId) });
      if (!Article) {
        res.send({ code: 403, message: "无此文章!" })
        return
      }

      user = await db.findOne('users', { _id: new ObjectId(Article.userId) });
      if (!user) {
        res.send({ code: 403, message: "文章无用户id!" })
        return
      }
      await db.disconnect();
    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }


    res.send({ code: 200, message: "获取成功!", data: { ...Article, username: user.Username } })

  },
  async addArticle (req, res, next) {
    const Article = req.body
    const token = req.headers.authorization
    const islogin = await getjwt(token, userJwt[Article.userId])
    if (!islogin) {
      res.send({ code: 401, message: "登录已过期请重新登录!" })
      return
    }
    const db = new Database();
    let users = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      // 插入数据
      const insertResult = await db.insertOne('ArticleList', {
        userId: Article.userId,
        title: Article.title,
        publicationTime: Article.publicationTime,
        content: Article.content,
        tags: Article.tags.split(','),
        viewCount: 0,
        comments: []
      });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }

    res.send({ code: 200, message: "发布成功!" })
  },
  async myArticleList (req, res, next) {
    const token = req.headers.authorization
    const islogin = await getjwt(token, userJwt[req.query.userId])
    if (!islogin) {
      res.send({ code: 401, message: "登录已过期请重新登录!" })
      return
    }
    const db = new Database();
    let list = null
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      list = await db.find('ArticleList', { userId: req.query.userId });
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.send({ code: 200, message: "获取成功!", data: list })

  },
  async editArticle (req, res, next) {
    const Article = req.body
    const ArticleId = new ObjectId(Article.ArticleId)
    Article.tags = Article.tags.split(',')
    const token = req.headers.authorization
    const islogin = await getjwt(token, userJwt[Article.userId])
    if (!islogin) {
      res.send({ code: 401, message: "登录已过期请重新登录!" })
      return
    }
    const db = new Database();
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      const newArticle = await db.findOne('ArticleList', { _id: ArticleId });
      if (!newArticle) {
        res.send({ code: 403, message: "该文章不存在,或者已经被删除!" })
        return
      }
      delete Article.userId;
      delete Article.ArticleId;
      // 更新数据
      const insertResult = await db.updateOne('ArticleList', { _id: ArticleId }, Article);
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.send({ code: 200, message: "更新成功!" })

  },
  async delArticle (req, res, next) {
    const ArticleId = new ObjectId(req.query.ArticleId)
    const token = req.headers.authorization
    const islogin = await getjwt(token, userJwt[req.query.userId])
    if (!islogin) {
      res.send({ code: 401, message: "登录已过期请重新登录!" })
      return
    }
    const db = new Database();
    try {
      await db.connect();
      const newArticle = await db.deleteMany('ArticleList', { _id: ArticleId });
      if (!newArticle) {
        res.send({ code: 403, message: "删除失败,无此文章!" })
      }
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.send({ code: 200, message: "删除成功!" })
  },
  async addComment (req, res, next) {
    const data = req.body
    const ArticleId = new ObjectId(data.ArticleId)
    const token = req.headers.authorization
    const islogin = await getjwt(token, userJwt[data.userId])
    if (!islogin) {
      res.send({ code: 401, message: "登录已过期请重新登录!" })
      return
    }
    const db = new Database();
    // 查询数据
    try {
      // // 连接数据库
      await db.connect();
      const Article = await db.findOne('ArticleList', { _id: ArticleId });
      if (!Article) {
        res.send({ code: 403, message: "文章不存在!" })
        return
      }
      Article.comments.push({
        userId: data.userId,
        commenterId: crypto.randomBytes(20).toString('hex'),
        commentText: data.commentText,
        timestamp: getYMDHMS()
      })
      // 更新数据
      const insertResult = await db.updateOne('ArticleList', { _id: ArticleId }, Article);
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }

    res.send({ code: 200, message: "评论成功!" })
  },
  async delComment (req, res, next) {
    const ArticleId = new ObjectId(req.query.ArticleId)
    // const token = req.headers.authorization
    // const islogin = await getjwt(token, userJwt[Article.userId])
    // if (!islogin) {
    //   res.send({ code: 401, message: "登录已过期请重新登录!" })
    //   return
    // }

    const db = new Database();
    try {
      await db.connect();
      const Article = await db.findOne('ArticleList', { _id: ArticleId });
      if (!Article) {
        res.send({ code: 403, message: "文章不存在!" })
        return
      }
      // Article.66728625f2366e32fa40e7d1
      Article.comments = Article.comments.filter(item => item.commenterId !== req.query.commenterId)
      // 更新数据
      const insertResult = await db.updateOne('ArticleList', { _id: ArticleId }, Article);
      await db.disconnect();

    } catch (error) {
      res.send({ code: 500, message: "数据库异常!" })
      return
    }
    res.send({ code: 200, message: "删除成功!" })
  }
}